<?php


namespace app\api\controller;


use app\admin\model\Banner;
use app\admin\model\GoodsCate;
use app\admin\model\GoodsCollect;
use app\admin\model\GoodsOrder;
use app\admin\model\User;
use app\admin\model\GoodsSkuValue;
use app\common\controller\Api;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\Address;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use think\Db;
use think\Env;

class Goods extends Api
{
    protected $noNeedLogin = ['banner', 'cate', 'list', 'recom', 'details'];
    protected $noNeedRight = ['*'];

    /**
     * 商城轮播
     *
     */
    public function banner()
    {
        $banner = Banner::where(['status' => 1, 'type' => 2])
            ->field('title,image')
            ->select();
        if (!empty($banner)) {
            foreach ($banner as &$v) {
                $v['image'] = Env::get('app.yuming') . $v['image'];
                $v->unsetAppend();
            }
        }

        $this->success('获取成功', $banner);
    }

    /**
     * 商城分类
     *
     */
    public function cate()
    {
        $cate = GoodsCate::where('status', 1)
            ->field('id,name,image')
            ->order('weigh asc')
            ->limit(0, 6)
            ->select();
        if (!empty($cate)) {
            foreach ($cate as &$v) {
                $v['image'] = Env::get('app.yuming') . $v['image'];
                $v->unsetAppend();
            }
        }
        $this->success('获取成功', $cate);
    }

    /**
     * 商城列表
     *
     */
    public function list()
    {
        $cata = input('cate_id');
        $keyword = input('keyword');    //关键字
        $page = input('page',1);
        $where = [];
        if (!empty($cata)) {
            $where['goods_cate_id'] = ['=', $cata];
        }
        if (!empty($keyword)) {
            $where['title'] = ['like', "%$keyword%"];
        }
        $goods = GoodsModel::where(['status' => 1, 'type' => 1])
            ->where($where)
            ->field('id,image,title,score,old_score,sell')
            ->order('is_top asc,weigh asc')
            ->page($page,8)
            ->select();
        $count = GoodsModel::where(['status' => 1, 'type' => 1])
            ->where($where)
            ->count();
        $maxpage = ceil($count / 8);
        if (!empty($goods)) {
            foreach ($goods as &$v) {
                $image = explode(',', $v['image']);
                if (isset($image[0])) {
                    $v['image'] = Env::get('app.yuming') . $image[0];
                }
                $v->unsetAppend();
            }
        }
        $data = ['goods'=>$goods,'count'=>$count,'maxpage'=>$maxpage];
        $this->success('获取成功', $data);
    }

    /**
     * 推荐商品
     *
     */
    public function recom()
    {
        $goods = GoodsModel::where(['is_top' => 1, 'status' => 1, 'type' => 1])
            ->field('id,image,title,score')
            ->order('weigh asc')
            ->limit(0, 4)
            ->select();
        if (!empty($goods)) {
            foreach ($goods as &$v) {
                $image = explode(',', $v['image']);
                if (isset($image[0])) {
                    $v['image'] = Env::get('app.yuming') . $image[0];
                }
                $v->unsetAppend();
            }
        }
        $this->success('获取成功', $goods);
    }


    /**
     * 商品详情
     *
     */
    public function details()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误，传入商品id');
        }
        $goods = GoodsModel::field('id,image,score,old_score,sell,title,subtitle,service,address,content,value_id')
            ->find($id);
        $value = GoodsSkuValue::where('id', 'in', $goods['value_id'])
            ->field('id,name,sku_id')
            ->select();
        $sku = [];
        foreach ($value as $vv) {
            $sku[$vv['sku_id']]['name'] = $vv['sku']['name'];
            unset($vv['sku']);
            $sku[$vv['sku_id']]['values'][] = $vv;
        }
        $goods['value_id'] = $sku;
        $image = explode(',', $goods['image']);
        $domain = [];
        foreach ($image as $vvv) {
            $domain[] = Env::get('app.yuming') . $vvv;
        }
        $goods['image'] = $domain;
        $goods['content'] = get_img_thumb_url($goods['content']);
        //$goods['out_time'] = date('Y-m-d H:i:s',$goods['out_time']);  //下架时间
        $goods->unsetAppend();
        //判断当前商品是否为当前登录用户的收藏商品
        $collect_list = GoodsCollect::where(['user_id' => $this->auth->id, 'goods_id' => $id])->find();
        if (empty($collect_list)) {
            $goods->collect = 0;
        } else {
            $goods->collect = 1;
        }
        $this->success('获取成功', $goods);
    }

    /**
     *
     * 积分兑换
     */
    public function exchange()
    {
        if ($this->request->isPost()) {
            $ress = Address::where(['is_default' => 1, 'user_id' => $this->auth->id])->find();
            $address_id = input('address_id', $ress['id']);     //收货地址
            $goods_id = input('goods_id');                      //商品
            $sku_id = input('value_id');                        //规格
            $goods = GoodsModel::field('id,title,subtitle,is_postage,image')->find($goods_id);
            $address = Address::field('id,name,phone,city,address,is_default')->find($address_id); //地址
            $goods->unsetAppend();
            $address->unsetAppend();
            $package = '包邮';       //运费
            if ($goods) {
                $image = explode(',', $goods['image']);
                if (isset($image[0])) {
                    $goods['image'] = Env::get('app.yuming') . $image[0];
                }
                if ($goods['is_postage'] != 1) {
                    $package = $goods['is_postage'];
                }
                $sku = '';
                if ($sku_id) {
                    $sku_value = GoodsSkuValue::where('id', 'in', $sku_id)
                        ->column('name');
                    $sku = implode(',', $sku_value);
                }
            }
            $data = ['address' => $address, 'goods' => $goods, 'package' => $package, 'sku_value' => $sku];
            $this->success('获取成功', $data);
        }
        $this->error('无效请求');
    }


    /**
     *
     * 提交订单
     */
    public function addOrder()
    {
        if ($this->request->isPost()) {
            $goods_id = input('goods_id');
            if (empty($goods_id)) {
                $this->error('请选择商品');
            }
            $address_id = input('address_id');
            if (empty($address_id)) {
                $this->error('请选择地址');
            }
            $value_id = input('value_id', '');   //规格id
            $num = input('num', 1);              //数量

            $goods = GoodsModel::where('id', $goods_id)
                ->field('id,title,subtitle,stock,is_postage,image,score,value_id')
                ->find();
            $score = $goods['score'] * $num;
            if (!$goods) {
                $this->error('商品错误');
            }
            if (!empty($goods['value_id'])) {
                if (empty($value_id)) {
                    $this->error('请选择商品规格');
                }
            }
            if ($goods['stock'] <= 0) {
                $this->error('商品库存不足');
            }
            $data = ['goods_score' => $score, 'member_score' => $this->auth->score];
            $this->success('获取成功', $data);
        }
        $this->error('无效请求');
    }

    /**
     *
     * 积分商品支付
     */
    public function payment()
    {
        if ($this->request->isPost()) {
            $goods_id = input('goods_id');              //商品id
            $address_id = input('address_id');          //地址id
            $value_id = input('value_id', '');   //规格id
            $remarks = input('remarks');                //备注
            $num = input('num', 1);              //数量
            $pay_password = input('pay_password');      //支付密码
            if (empty($goods_id) || empty($address_id)) {
                $this->error('缺少参数');
            }
            $user = User::find($this->auth->id);
            $goods = GoodsModel::where('id', $goods_id)
                ->field('id,title,subtitle,postage,stock,is_postage,image,score,value_id')
                ->find();
            if (!$goods) {
                $this->error('商品错误');
            }
            if (!empty($goods['value_id'])) {
                if (empty($value_id)) {
                    $this->error('请选择商品规格');
                }
            }
            if ($goods['stock'] <= 0) {
                $this->error('商品库存不足');
            }
            $score = $goods['score'] * $num;
            $package = 0;
            if ($user['score'] < $score) {
                $this->error('您的积分不足');
            }
            $money_log = [];
            if ($goods['is_postage'] != 1) {  //不包邮
                if ($user['money'] < $goods['postage']) {
                    $this->error('该商品需支付' . $goods['postage'] . '元运费,您的余额不足,请充值后兑换');
                }
                $package = $goods['postage'];
                //类型:1=推荐奖励,2=未拼中，返回购买金额,3=未拼中，奖励余额,4=:拼中10次，奖励余额,5=充值,6=助力红包,-1=拼购支付,-2=提现,7=运费扣除
                //5=助力红包,6=拼购支付,7=提现,8=运费扣除,9=拒绝提现 返回余额
                $userMoney = MoneyLog::where(['user_id' => $this->auth->id])->order('createtime desc')->find();
                if (empty($user)){
                    $money_log = [
                        'before' => $user['money'],
                        'after' => $user['money'] - $package,
                        'money' => $package,
                        'type' => 7,
                        'status' => -1,
                        'memo' => '积分商品运费扣除',
                        'user_id' => $this->auth->id
                    ];
                }else{
                    $money_log = [
                        'before' => $userMoney['after'],
                        'after' => $userMoney['after'] - $package,
                        'money' => $package,
                        'type' => 7,
                        'status' => -1,
                        'memo' => '积分商品运费扣除',
                        'user_id' => $this->auth->id
                    ];
                }
            }
            if (empty($pay_password)) {
                $this->error('请输入密码');
            }
            $pwd = getPassword($pay_password, $user['pay_salt']);
            if ($pwd != $user['pay_password']) {
                $this->error('支付密码错误');
            }
            //订单
            $orderData = [
                'user_id' => $this->auth->id,
                'goods_id' => $goods_id,
                'address_id' => $address_id,
                'value_id' => $value_id,
                'type' => 2,
                'buy_num' => $num,
                'pay_price' => $score,
                'beizhu' => $remarks,
                'order_num' => OrderNum(),
                'status' => 1
            ];
            $userScore = ScoreLog::where(['user_id' => $this->auth->id])->order('createtime desc')->find();
            if (empty($userScore)){
                $scoreLog = [
                    'user_id' => $this->auth->id,
                    'score' => $score,
                    'before' => $userScore['after'],
                    'after' => $userScore['after'] - $score,
                    'memo' => '兑换商品所花费积分',
                    'status' => -1,
                    'type' => 1
                ];
            }else{
                $scoreLog = [
                    'user_id' => $this->auth->id,
                    'score' => $score,
                    'before' => $user['score'],
                    'after' => $user['score'] - $score,
                    'memo' => '兑换商品所花费积分',
                    'status' => -1,
                    'type' => 1
                ];
            }
            Db::startTrans();
            try {
                GoodsOrder::create($orderData);                 //订单
                ScoreLog::create($scoreLog);                    //积分变动记录
                if (!empty($money_log)) {
                    MoneyLog::create($money_log);               //余额变动记录
                }
                GoodsModel::where('id', $goods_id)
                    ->inc('sell',$num)  //加销量
                    ->dec('stock',$num)  //减库存
                    ->update();                                 //商品库存变动
                User::where('id', $this->auth->id)
                    ->dec('score', $score)  //积分
                    ->dec('money', $package)  //余额
                    ->update();                                 //用户积分余额变动
                // 提交事务
                Db::commit();
                return sucessMsg('兑换成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('兑换失败',$e->getMessage());
            }
        }
        return errMsg(0,'无效请求');
    }
}